package com.hzy.fivepalace.db.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.hzy.fivepalace.common.consts.RedisKeyConsts;
import com.hzy.fivepalace.common.exception.TransactionalException;
import com.hzy.fivepalace.common.exception.WxPayCallbackException;
import com.hzy.fivepalace.common.service.redis.RedisCache;
import com.hzy.fivepalace.common.type.CommissionIssueStatusTypeEnums;
import com.hzy.fivepalace.common.type.CommissionIssueTypeEnums;
import com.hzy.fivepalace.common.type.OrderStatusEnums;
import com.hzy.fivepalace.common.type.VipTypeEnums;
import com.hzy.fivepalace.db.dao.AppUserCommissionDetaiMapper;
import com.hzy.fivepalace.db.dao.DtsGroupOpenListMapper;
import com.hzy.fivepalace.db.dao.DtsOrderGoodsMapper;
import com.hzy.fivepalace.db.dao.ex.DtsCouponUserMapperEx;
import com.hzy.fivepalace.db.dao.ex.DtsUserMapperEx;
import com.hzy.fivepalace.db.dao.ex.GoodsProductMapper;
import com.hzy.fivepalace.db.domain.*;
import jodd.util.StringUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 支付服务实现
 */
@Service
public class PayService {
    private static Logger log = LoggerFactory.getLogger(PayService.class);

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private DtsVipConfigService dtsVipConfigService;

    @Resource
    private Redisson redisson;

    @Autowired
    private DtsOrderService dtsOrderService;

    @Autowired
    private DtsGoodsService dtsGoodsService;

    @Resource
    private DtsOrderGoodsMapper dtsOrderGoodsMapper;

    @Resource
    private RedisCache redisCache;

    @Autowired
    private DtsOrderService orderService;
    @Resource
    private GoodsProductMapper goodsProductMapper;
    @Resource
    private DtsCouponUserMapperEx couponUserMapperEx;
    @Autowired
    private DtsUserService userService;
    @Resource
    private AppUserCommissionDetaiMapper userCommissionDetaiMapper;
    @Resource
    private DtsUserMapperEx dtsUserMapperEx;
    @Resource
    private DtsGroupOpenListService groupOpenListService;
    @Resource
    private DtsGroupOpenListMapper groupOpenListMapper;
    @Resource
    private DtsGroupProductService groupProductService;
    @Resource
    private DtsGroupOpenDetailService groupOpenDetailService;

    /**
     * 支付完成后处理
     *
     * @param order
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void payment(DtsOrder order) {
        try {
            //删除订单过期监听
            redisCache.deleteObject(RedisKeyConsts.ORDER_TIME_OUT_LISTENING_KEY + order.getOrderSn());
        }catch (Exception e){
            e.printStackTrace();
        }

        if (!order.getIsByVip()) {//购买商品
            DtsOrderWithBLOBs orderUpd = new DtsOrderWithBLOBs();
            orderUpd.setId(order.getId());
            if (order.getFreightType().intValue() == 0) {//配送方式为物流
                //订单状状态改为待发货
                orderUpd.setOrderStatus((short) OrderStatusEnums.TYPE1.getType());
            } else {//配送方式为自提
                //订单状状态改为待收货
                orderUpd.setOrderStatus((short) OrderStatusEnums.TYPE2.getType());
            }
            orderUpd.setPayTime(LocalDateTime.now());
            orderUpd.setEndTime(LocalDateTime.now());
            orderUpd.setActualPrice(order.getOrderPrice());
            orderUpd.setUpdateTime(LocalDateTime.now());
            dtsOrderService.updateById(orderUpd);
            //查询订单商品信息
            DtsOrderGoodsExample orderGoodsExample = new DtsOrderGoodsExample();
            orderGoodsExample.createCriteria().andOrderIdEqualTo(order.getId()).andDeletedEqualTo(false);
            List<DtsOrderGoods> goodsList = dtsOrderGoodsMapper.selectByExample(orderGoodsExample);

            goodsList.forEach(item -> {
                //增加商品销量
                DtsGoods goods = dtsGoodsService.getById(item.getGoodsId());
                if (null != goods) {
                    goods.setSales(goods.getSales() + item.getNumber());
                    dtsGoodsService.updateById(goods);
                }
            });

            //分佣实现
            DtsUser user = userService.findById(order.getUserId());//获取当前用户信息
            if(null == user){
                return;
            }

            //处理拼团问题
            if(order.getOrderType() == 1){

                DtsOrderWithBLOBs tempOrder = new DtsOrderWithBLOBs();
                tempOrder.setId(order.getId());
                //13 - 已付款等待成团
                tempOrder.setOrderStatus((short) OrderStatusEnums.TYPE13.getType());

                //拼团活动
                DtsGroupProduct groupProduct = groupProductService.findById(order.getGroupId());

                //查看当前是否有未满员的拼图
                QueryWrapper<DtsGroupOpenList> qw = new QueryWrapper<>();
                qw.eq("group_id", order.getGroupId());
                qw.eq("state", 0);// 未满员状态
                qw.last("limit 1");
                DtsGroupOpenList groupOpenList = groupOpenListService.getOne(qw);
                //如果不存在 未满员的团购的话，重新创建
                if(groupOpenList == null){
                    //DtsUser user, DtsGroupProduct groupProduct, DtsOrder order, int isOwner
                    groupOpenList = groupOpenListService.addGroupOpen(user, groupProduct, order,1);
                    order.setIsPinkOwner(1);
                }
                order.setPinkId(groupOpenList.getId());
                tempOrder.setPinkId(groupOpenList.getId());
                int ret = orderService.updateById(tempOrder);
                if(ret <=0){
                    throw new TransactionalException("orderService updateById error");
                }

                //参与人  添加团购记录
                ret = groupOpenDetailService.addGroupOpenDetail(user, groupOpenList, order);
                if(ret > 0){
                    int userCount = groupOpenList.getUserCount();
                    int buyUserCount = groupOpenList.getBuyUserCount();
                    // 当前参团人员 人数+1
                    buyUserCount += 1;
                    //人已经满员
                    if(buyUserCount >= userCount){
                        //已达人数
                        //状态  0 - 未达到人数  1 - 已经达到人数  2 - 团购已成功结束（已完成团购） 3 - 团购未达到人数 团购失败
                        groupOpenList.setState(1);
                        // 拼团成功  各成员 发送 成功推送
                        QueryWrapper<DtsGroupOpenDetail> qwOpenDetail = new QueryWrapper<>();
                        qwOpenDetail.eq("group_open_id",groupOpenList.getId());
                        List<DtsGroupOpenDetail> openDetails = groupOpenDetailService.list(qwOpenDetail);
                        if(CollUtil.isNotEmpty(openDetails)){
                            for (DtsGroupOpenDetail openDetail : openDetails){
                                openDetail.setState(1);
                                boolean bl = groupOpenDetailService.updateById(openDetail);
                                if(!bl){
                                    throw new TransactionalException("groupOpenDetailService updateById error");
                                }

                                DtsOrderWithBLOBs userOrder = orderService.findById(openDetail.getOrderId());
                                if(userOrder!= null){
                                    if (userOrder.getFreightType().intValue() == 0) {//配送方式为物流
                                        //订单状状态改为待发货
                                        userOrder.setOrderStatus((short) OrderStatusEnums.TYPE1.getType());
                                    } else {//配送方式为自提
                                        //订单状状态改为待收货
                                        userOrder.setOrderStatus((short) OrderStatusEnums.TYPE2.getType());
                                    }
                                    orderService.updateById(userOrder);
                                }
                            }
                        }
                    }else{
                    }
                    groupOpenList.setBuyUserCount(buyUserCount);
                    ret = groupOpenListMapper.updateById(groupOpenList);
                    if(ret <=0){
                        throw new TransactionalException("groupOpenListMapper updateById error");
                    }
                }

                //发送开团成功通知
                //给团长发送
            }



            //推荐人用户id
            if (user.getRecodeUserId().equals(0)) {
                return;
            }
            //获取用户推荐人信息
            DtsUser reUser = userService.findById(user.getRecodeUserId());
            if(null==reUser){
                return;
            }
            //获取推荐人会员等级
            VipTypeEnums reUserVipType = VipTypeEnums.getEnum(reUser.getVipType());
            if (null == reUserVipType) {
                return;
            }

            //获取推荐人的上级
            DtsUser toReUser =null;
            if (!reUser.getRecodeUserId().equals(0)) {
                toReUser= userService.findById(reUser.getRecodeUserId());
            }

            for (DtsOrderGoods item:goodsList){
                //获取商品佣金比例配置
                DtsVipConfig scaleConfig=dtsVipConfigService.getGoodsExtendScale(reUserVipType.getId(),item.getProductId());
                if(null!=scaleConfig){
                    BigDecimal goodsOneLevelExtendAmount=order.getGoodsPrice().multiply(scaleConfig.getGoodsOneLevelExtendScale());
                    if(goodsOneLevelExtendAmount.compareTo(new BigDecimal("0.01"))>=0){
                        AppUserCommissionDetai reUserCommissionDetai = new AppUserCommissionDetai();//推荐人佣金明细对象
                        reUserCommissionDetai.setToUserId(order.getUserId());
                        reUserCommissionDetai.setUserId(reUser.getId());
                        reUserCommissionDetai.setAddTime(LocalDateTime.now());
                        reUserCommissionDetai.setAmount(goodsOneLevelExtendAmount);
                        reUserCommissionDetai.setOrderId(order.getId());
                        reUserCommissionDetai.setIssueStatus(CommissionIssueStatusTypeEnums.TYPE1.getId());
                        reUserCommissionDetai.setIssueTime(LocalDateTime.now());
                        reUserCommissionDetai.setParticularsMatter("购买产品");
                        reUserCommissionDetai.setCommissionType(CommissionIssueTypeEnums.TYPE1.getId());
                        reUserCommissionDetai.setScale(scaleConfig.getGoodsOneLevelExtendScale());
                        userCommissionDetaiMapper.insertSelective(reUserCommissionDetai);
                        dtsUserMapperEx.addUserCommission(reUser.getId(), goodsOneLevelExtendAmount);
                    }

                    if (reUserVipType.getId() != VipTypeEnums.TYPE1.getId()&&null!=toReUser) {///如果当前推荐人等级不为PLUS会员，而是其他的，并且推荐人有上一级,那就要给推荐人的推荐人分佣
                        BigDecimal goodsTwoLevelExtendAmount=order.getGoodsPrice().multiply(scaleConfig.getGoodsTwoLevelExtendScale());
                        if(goodsTwoLevelExtendAmount.compareTo(new BigDecimal("0.01"))>=0){
                            AppUserCommissionDetai toReUserCommissionDetai =new AppUserCommissionDetai();//推荐人的推荐人佣金明细对象
                            toReUserCommissionDetai.setToUserId(reUser.getId());
                            toReUserCommissionDetai.setUserId(toReUser.getId());
                            toReUserCommissionDetai.setAddTime(LocalDateTime.now());
                            toReUserCommissionDetai.setAmount(goodsTwoLevelExtendAmount);
                            toReUserCommissionDetai.setOrderId(order.getId());
                            toReUserCommissionDetai.setIssueStatus(CommissionIssueStatusTypeEnums.TYPE1.getId());
                            toReUserCommissionDetai.setIssueTime(LocalDateTime.now());
                            toReUserCommissionDetai.setParticularsMatter("推广的用户购买产品");
                            toReUserCommissionDetai.setCommissionType(CommissionIssueTypeEnums.TYPE1.getId());
                            toReUserCommissionDetai.setScale(scaleConfig.getGoodsTwoLevelExtendScale());
                            userCommissionDetaiMapper.insertSelective(toReUserCommissionDetai);
                            dtsUserMapperEx.addUserCommission(toReUser.getId(), goodsTwoLevelExtendAmount);
                        }
                    }
                }
            }

        } else {//购买会员
            DtsUser user = userService.findById(order.getUserId());
            if (null != user) {//更新用户会员类型
                DtsUser userUpd = new DtsUser();
                userUpd.setId(user.getId());
                userUpd.setVipType(order.getVipType());
                userService.updateById(userUpd);
            }

            //修改订单状态
            DtsOrderWithBLOBs orderUpd = new DtsOrderWithBLOBs();
            orderUpd.setId(order.getId());
            orderUpd.setOrderStatus((short) OrderStatusEnums.TYPE3.getType());
            orderUpd.setPayTime(LocalDateTime.now());
            orderUpd.setEndTime(LocalDateTime.now());
            orderUpd.setActualPrice(order.getOrderPrice());
            orderUpd.setUpdateTime(LocalDateTime.now());
            dtsOrderService.updateById(orderUpd);
            dtsOrderService.addVipSales(order.getVipType());

            if (null != user && !user.getRecodeUserId().equals(0)) {//如果该用户有推荐用户，那就查询推荐用户信息
                DtsUser reUser = userService.findById(user.getRecodeUserId());
                if (null != reUser) {
                    //获取推荐用户会员类型
                    VipTypeEnums reUserVipType = VipTypeEnums.getEnum(reUser.getVipType());
                    if (null != reUserVipType) {
                        VipTypeEnums nextReUserVipType = null;//推荐用户下一会员等级
                        if (reUserVipType.getId() == VipTypeEnums.TYPE1.getId()) {//如果当前等级是PLUS会员
                            nextReUserVipType = VipTypeEnums.TYPE2;//那么下一等级就是代理商
                        } else if (reUserVipType.getId() == VipTypeEnums.TYPE2.getId()) {//如果当前等级是代理商
                            nextReUserVipType = VipTypeEnums.TYPE3;//那么下一等级就是合伙人
                        } else if (reUserVipType.getId() == VipTypeEnums.TYPE3.getId()) {//如果当前等级是合伙人
                            nextReUserVipType = VipTypeEnums.TYPE4;//那么下一等级就是股东
                        }
                        if (null != nextReUserVipType) {//有下一等级就进入升级逻辑
                            //获取下一会员配置信息
                            DtsVipConfig nextVipConfig = dtsVipConfigService.getVipConfigByVipType(nextReUserVipType.getId());
                            if (null != nextVipConfig) {
                                //获取该推荐人现会员等级推广总人数
                                Integer currentVipExtendCount = dtsOrderService.getUserVipSumExtendCount(reUser.getId(), reUserVipType.getId());
                                if (currentVipExtendCount.intValue() >= nextVipConfig.getExtendCount().intValue()) {//如果满足下一会员升级条件就直接升级
                                    DtsUser reUserUpd = new DtsUser();
                                    reUserUpd.setId(reUser.getId());
                                    reUserUpd.setVipType(nextVipConfig.getVipType());
                                    reUserVipType = VipTypeEnums.getEnum(nextVipConfig.getVipType());
                                    userService.updateById(reUserUpd);
                                }
                            }
                        }

                        if (null != reUserVipType) {//给推荐人分佣
                            //用户充值的会员类型
                            VipTypeEnums topUpVipType = VipTypeEnums.getEnum(order.getVipType());
                            if (null != topUpVipType) {

                                //获取充值的会员详情
                                DtsVipConfig topUpVipVipConfig = dtsVipConfigService.getVipConfigByVipType(topUpVipType.getId());

                                if (null != topUpVipVipConfig) {
                                    AppUserCommissionDetai reUserCommissionDetai = null;//推荐人佣金明细对象
                                    AppUserCommissionDetai toReUserCommissionDetai = null;//推荐人的推荐人佣金明细对象


                                    //获取推荐人的上级
                                    DtsUser toReUser =null;
                                    if(!reUser.getRecodeUserId().equals(0)){
                                        toReUser=userService.findById(reUser.getRecodeUserId());
                                    }

                                    if (reUserVipType.getId() == VipTypeEnums.TYPE1.getId()) {//如果当前推荐人等级是PLUS会员

                                        if (topUpVipVipConfig.getVipType().intValue() == VipTypeEnums.TYPE1.getId()) {//如果充值的是PLUS会员
                                            reUserCommissionDetai = new AppUserCommissionDetai();
                                            reUserCommissionDetai.setToUserId(order.getUserId());
                                            reUserCommissionDetai.setUserId(reUser.getId());
                                            reUserCommissionDetai.setAddTime(LocalDateTime.now());
                                            reUserCommissionDetai.setAmount(topUpVipVipConfig.getOneLevelExtendAmount());
                                            reUserCommissionDetai.setOrderId(order.getId());
                                            reUserCommissionDetai.setIssueStatus(CommissionIssueStatusTypeEnums.TYPE1.getId());
                                            reUserCommissionDetai.setIssueTime(LocalDateTime.now());
                                            reUserCommissionDetai.setParticularsMatter("购买成为" + topUpVipType.getDesc());
                                            reUserCommissionDetai.setCommissionType(CommissionIssueTypeEnums.TYPE1.getId());
                                            reUserCommissionDetai.setScale(new BigDecimal("0"));
                                        }

                                    } else if (reUserVipType.getId() == VipTypeEnums.TYPE2.getId()) {//如果当前推荐人等级是代理商

                                        if (topUpVipVipConfig.getVipType().intValue() == VipTypeEnums.TYPE1.getId()) {//如果充值的是PLUS会员
                                            reUserCommissionDetai = new AppUserCommissionDetai();
                                            reUserCommissionDetai.setToUserId(order.getUserId());
                                            reUserCommissionDetai.setUserId(reUser.getId());
                                            reUserCommissionDetai.setAddTime(LocalDateTime.now());
                                            reUserCommissionDetai.setAmount(topUpVipVipConfig.getOneLevelExtendAmount());
                                            reUserCommissionDetai.setOrderId(order.getId());
                                            reUserCommissionDetai.setIssueStatus(CommissionIssueStatusTypeEnums.TYPE1.getId());
                                            reUserCommissionDetai.setIssueTime(LocalDateTime.now());
                                            reUserCommissionDetai.setParticularsMatter("购买成为" + topUpVipType.getDesc());
                                            reUserCommissionDetai.setCommissionType(CommissionIssueTypeEnums.TYPE1.getId());
                                            reUserCommissionDetai.setScale(new BigDecimal("0"));
                                            if (null != toReUser) {//给推荐人的推荐人分佣
                                                toReUserCommissionDetai = new AppUserCommissionDetai();
                                                toReUserCommissionDetai.setToUserId(reUser.getId());
                                                toReUserCommissionDetai.setUserId(toReUser.getId());
                                                toReUserCommissionDetai.setAddTime(LocalDateTime.now());
                                                toReUserCommissionDetai.setAmount(topUpVipVipConfig.getTwoLevelExtendAmount());
                                                toReUserCommissionDetai.setOrderId(order.getId());
                                                toReUserCommissionDetai.setIssueStatus(CommissionIssueStatusTypeEnums.TYPE1.getId());
                                                toReUserCommissionDetai.setIssueTime(LocalDateTime.now());
                                                toReUserCommissionDetai.setParticularsMatter("推广" + topUpVipType.getDesc());
                                                toReUserCommissionDetai.setCommissionType(CommissionIssueTypeEnums.TYPE1.getId());
                                                toReUserCommissionDetai.setScale(new BigDecimal("0"));
                                            }
                                        }


                                    } else if (reUserVipType.getId() == VipTypeEnums.TYPE3.getId()) {//如果当前推荐人等级是合伙人

                                        if (topUpVipVipConfig.getVipType().intValue() == VipTypeEnums.TYPE1.getId() || topUpVipVipConfig.getVipType().intValue() == VipTypeEnums.TYPE2.getId()) {//如果充值的是PLUS会员、代理商
                                            reUserCommissionDetai = new AppUserCommissionDetai();
                                            reUserCommissionDetai.setToUserId(order.getUserId());
                                            reUserCommissionDetai.setUserId(reUser.getId());
                                            reUserCommissionDetai.setAddTime(LocalDateTime.now());
                                            reUserCommissionDetai.setAmount(topUpVipVipConfig.getOneLevelExtendAmount());
                                            reUserCommissionDetai.setOrderId(order.getId());
                                            reUserCommissionDetai.setIssueStatus(CommissionIssueStatusTypeEnums.TYPE1.getId());
                                            reUserCommissionDetai.setIssueTime(LocalDateTime.now());
                                            reUserCommissionDetai.setParticularsMatter("购买成为" + topUpVipType.getDesc());
                                            reUserCommissionDetai.setCommissionType(CommissionIssueTypeEnums.TYPE1.getId());
                                            reUserCommissionDetai.setScale(new BigDecimal("0"));
                                            if (null != toReUser) {//给推荐人的推荐人分佣
                                                toReUserCommissionDetai = new AppUserCommissionDetai();
                                                toReUserCommissionDetai.setToUserId(reUser.getId());
                                                toReUserCommissionDetai.setUserId(toReUser.getId());
                                                toReUserCommissionDetai.setAddTime(LocalDateTime.now());
                                                toReUserCommissionDetai.setAmount(topUpVipVipConfig.getTwoLevelExtendAmount());
                                                toReUserCommissionDetai.setOrderId(order.getId());
                                                toReUserCommissionDetai.setIssueStatus(CommissionIssueStatusTypeEnums.TYPE1.getId());
                                                toReUserCommissionDetai.setIssueTime(LocalDateTime.now());
                                                toReUserCommissionDetai.setParticularsMatter("推广" + topUpVipType.getDesc());
                                                toReUserCommissionDetai.setCommissionType(CommissionIssueTypeEnums.TYPE1.getId());
                                                toReUserCommissionDetai.setScale(new BigDecimal("0"));
                                            }
                                        }


                                    } else if (reUserVipType.getId() == VipTypeEnums.TYPE4.getId()) {//如果当前推荐人等级是股东

                                        reUserCommissionDetai = new AppUserCommissionDetai();
                                        reUserCommissionDetai.setToUserId(order.getUserId());
                                        reUserCommissionDetai.setUserId(reUser.getId());
                                        reUserCommissionDetai.setAddTime(LocalDateTime.now());
                                        reUserCommissionDetai.setAmount(topUpVipVipConfig.getOneLevelExtendAmount());
                                        reUserCommissionDetai.setOrderId(order.getId());
                                        reUserCommissionDetai.setIssueStatus(CommissionIssueStatusTypeEnums.TYPE1.getId());
                                        reUserCommissionDetai.setIssueTime(LocalDateTime.now());
                                        reUserCommissionDetai.setParticularsMatter("购买成为" + topUpVipType.getDesc());
                                        reUserCommissionDetai.setCommissionType(CommissionIssueTypeEnums.TYPE1.getId());
                                        reUserCommissionDetai.setScale(new BigDecimal("0"));
                                        if (null != toReUser) {//给推荐人的推荐人分佣
                                            toReUserCommissionDetai = new AppUserCommissionDetai();
                                            toReUserCommissionDetai.setToUserId(reUser.getId());
                                            toReUserCommissionDetai.setUserId(toReUser.getId());
                                            toReUserCommissionDetai.setAddTime(LocalDateTime.now());
                                            toReUserCommissionDetai.setAmount(topUpVipVipConfig.getTwoLevelExtendAmount());
                                            toReUserCommissionDetai.setOrderId(order.getId());
                                            toReUserCommissionDetai.setIssueStatus(CommissionIssueStatusTypeEnums.TYPE1.getId());
                                            toReUserCommissionDetai.setIssueTime(LocalDateTime.now());
                                            toReUserCommissionDetai.setParticularsMatter("推广" + topUpVipType.getDesc());
                                            toReUserCommissionDetai.setCommissionType(CommissionIssueTypeEnums.TYPE1.getId());
                                            toReUserCommissionDetai.setScale(new BigDecimal("0"));
                                        }

                                    }


                                    if (null != reUserCommissionDetai) {
                                        if(reUserCommissionDetai.getAmount().compareTo(new BigDecimal("0"))>0){
                                            //添加推荐人的佣金
                                            dtsUserMapperEx.addUserCommission(reUserCommissionDetai.getUserId(),reUserCommissionDetai.getAmount());
                                            userCommissionDetaiMapper.insertSelective(reUserCommissionDetai);
                                        }

                                    }
                                    if (null != toReUserCommissionDetai) {
                                        if(toReUserCommissionDetai.getAmount().compareTo(new BigDecimal("0"))>0) {
                                            //添加推荐人的推荐人佣金
                                            dtsUserMapperEx.addUserCommission(toReUserCommissionDetai.getUserId(), toReUserCommissionDetai.getAmount());
                                            userCommissionDetaiMapper.insertSelective(toReUserCommissionDetai);
                                        }

                                    }


                                }

                            }


                        }


                    }
                }
            }
        }

    }

    /**
     * 微信退款回调
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Object refundCallbackWx (HttpServletRequest request, HttpServletResponse response){
        String xmlResult = null;
        try {
            xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        } catch (IOException e) {
            log.error("微信退款回调失败：{}", "获取回调消息内容错误!");
            throw new WxPayCallbackException(e.getMessage());
        }
        WxPayRefundNotifyResult result = null;
        String orderNo = "";
        try {
            result = wxPayService.parseRefundNotifyResult(xmlResult);
            //订单编号
            orderNo = result.getReqInfo().getOutTradeNo();
        } catch (WxPayException e) {
            log.error("微信退款回调失败：{}", "格式化消息内容错误!");
            throw new WxPayCallbackException(e.getMessage());
        }

        if (StringUtils.isBlank(orderNo)) {
            log.error("微信退款回调失败：{}", "订单编号为空");
            return WxPayNotifyResponse.fail("订单编号为空");
        }


        // 根据订单编号加锁
        RLock lock = redisson.getLock("wx.refundCallbackWx." + orderNo);
        if (lock.isLocked()) {
            log.info("微信退款重复回调,订单号编号:{}", orderNo);
            return WxPayNotifyResponse.fail("请求频繁");
        }
        lock.lock(30, TimeUnit.MINUTES);

        DtsOrderWithBLOBs order = dtsOrderService.selectOrderWithBLOBsByOrderNo(orderNo);
        if (null == order || order.getIsByVip()) {
            log.error("微信退款回调失败：{},orderNo:{}", "订单不存在", orderNo);
            lock.unlock();
            return WxPayNotifyResponse.fail("订单不存在");
        }

        if (order.getDeleted()) {
            log.error("微信退款回调失败：{},orderId:{}", "订单已被删除", order.getId());
            lock.unlock();
            return WxPayNotifyResponse.fail("订单已被删除");
        }
        //判断订单状态
        if (order.getOrderStatus().intValue() != OrderStatusEnums.TYPE7.getType()) {
            log.error("微信退款回调失败：{},orderNo:{}，订单状态:{}", "订单状态不支持!", orderNo, OrderStatusEnums.getEnum(order.getOrderStatus().intValue()).getName());
            lock.unlock();
            return WxPayNotifyResponse.fail("订单状态不支持");
        }

        //处理业务逻辑
        try {
            //使用的优惠券id
            Integer couponsId = order.getCouponsId();
            DtsOrderWithBLOBs orderUpd = new DtsOrderWithBLOBs();
            orderUpd.setId(order.getId());
            if (StringUtils.equals("本次售后完成,由商家操作退款", order.getRefundDesc())) {
                //售后退款，订单状态就为售后完成
                orderUpd.setOrderStatus((short) OrderStatusEnums.TYPE10.getType());
            } else {//极速退款
                //订单状态改完已退款
                orderUpd.setOrderStatus((short) OrderStatusEnums.TYPE5.getType());
            }
            orderUpd.setUpdateTime(LocalDateTime.now());
            //退款时间为当前时间
            orderUpd.setRefundTime(LocalDateTime.now());
            orderService.updateById(orderUpd);
            //查询订单商品信息
            DtsOrderGoodsExample orderGoodsExample = new DtsOrderGoodsExample();
            orderGoodsExample.createCriteria().andOrderIdEqualTo(order.getId()).andDeletedEqualTo(false);
            List<DtsOrderGoods> goodsList = dtsOrderGoodsMapper.selectByExample(orderGoodsExample);
            goodsList.forEach(item -> {
                //恢复货品库存
                goodsProductMapper.addStock(item.getProductId(), item.getNumber().shortValue());
            });
            if (null != couponsId && couponsId.intValue() > 0) {//使用了优惠券就更改优惠券为未使用
                couponUserMapperEx.setCouponsStatusIsNoUse(couponsId);
            }
        } catch (Exception e) {
            log.error("微信退款回调失败:{},orderNo:{},msg:{}", "处理业务逻辑", orderNo, e.getMessage());
            lock.unlock();
            throw new WxPayCallbackException(e.getMessage());
        }
        log.info("【请求结束】微信退款回调:响应结果:{},orderNo:{}", "处理成功!", orderNo);
        lock.unlock();
        return WxPayNotifyResponse.success("处理成功!");
    }

    /**
     * 微信支付回调
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public Object payCallbackWx (HttpServletRequest request, HttpServletResponse response){
        String xmlResult = null;
        try {
            xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        } catch (IOException e) {
            log.error("微信支付回调失败：{}", "获取回调消息内容错误!");
            throw new WxPayCallbackException(e.getMessage());
        }

        WxPayOrderNotifyResult result = null;
        try {
            result = wxPayService.parseOrderNotifyResult(xmlResult);
        } catch (WxPayException e) {
            log.error("微信支付回调失败：{}", "格式化消息内容错误!");
            throw new WxPayCallbackException(e.getMessage());
        }
        System.out.println("微信回调接收参数：开始=====" );
        System.out.println(result.toString());
        System.out.println("微信回调接收参数：结束=====");
        //订单编号
        String orderNo = result.getOutTradeNo();
        if (StringUtil.isBlank(orderNo)) {
            log.error("微信支付回调失败：{}", "订单编号为空");
            return WxPayNotifyResponse.fail("订单编号为空");
        }

        // 根据订单编号加锁
        RLock lock = redisson.getLock("wx.payCallbackWx." + orderNo);
        if (lock.isLocked()) {
            log.info("微信支付重复回调,订单号编号:{}", orderNo);
            return WxPayNotifyResponse.fail("请求频繁");
        }
        lock.lock(30, TimeUnit.MINUTES);

        DtsOrder order = dtsOrderService.selectAppOrderByOrderNoOrOutTradeNo(orderNo);
        if (null == order) {
            log.error("微信支付回调失败：{},orderNo:{}", "订单不存在", orderNo);
            lock.unlock();
            return WxPayNotifyResponse.fail("订单不存在");
        }

        if (order.getDeleted()) {
            log.error("微信支付回调失败：{},orderId:{}", "订单已被删除", order.getId());
            lock.unlock();
            return WxPayNotifyResponse.fail("订单已被删除");
        }

        //支付的总金额
        String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());

        //判断订单状态
        if (order.getOrderStatus().intValue() != OrderStatusEnums.TYPE0.getType()) {
            log.error("微信支付回调失败：{},orderNo:{}，订单状态:{}", "订单状态不支持!", orderNo, OrderStatusEnums.getEnum(order.getOrderStatus().intValue()).getName());
            lock.unlock();
            return WxPayNotifyResponse.fail("订单状态不支持");
        }

        if (!totalFee.equals(order.getOrderPrice().toString())) {
            log.error("微信支付回调失败：{}", "支付金额不符合,orderNo:{},实付:{},需付:{}", orderNo, totalFee, order.getOrderPrice());
            lock.unlock();
            return WxPayNotifyResponse.fail("支付金额不符合");
        }

        try {
            //支付完成后处理
            payment(order);
        } catch (Exception e) {
            log.error("微信支付回调失败:{},orderNo:{},msg:{}", "支付完成后处理异常", orderNo, e.getMessage());
            lock.unlock();
            throw new WxPayCallbackException(e.getMessage());
        }

        log.info("【请求结束】微信支付回调:响应结果:{},orderNo:{}", "处理成功!", orderNo);
        lock.unlock();
        return WxPayNotifyResponse.success("处理成功!");
    }

}
